import FoodTruckList from "@/components/food-trucks/FoodTruckList";
import FoodTruckSearch from "@/components/food-trucks/FoodTruckSearch";
import { getAllFoodTrucks } from "@/services";
import { useRouter } from "next/router";
import Head from "next/head";
import { useState } from "react";

const FoodTrucksPage = ({ allFoodTrucks }) => {
  const [foodTrucks, setFoodTrucks] = useState(allFoodTrucks);
  const router = useRouter();
  const findFoodTruckHandler = async (params) => {
    const res = await fetch("/api/food-trucks", {
      method: "post",
      body: JSON.stringify(params),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());

    setFoodTrucks(res.data);
  };

  const likeHandler = async (params) => {
    const res = await fetch("/api/food-truck/like", {
      method: "put",
      body: JSON.stringify(params),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());

    const data = res.data;
    const i = foodTrucks.findIndex(({ id }) => id == data.id);

    setFoodTrucks([
      ...foodTrucks.slice(0, i),
      res.data,
      ...foodTrucks.slice(i + 1),
    ]);
  };

  const collectionHandler = async (params) => {
    const res = await fetch("/api/food-truck/collect", {
      method: "put",
      body: JSON.stringify(params),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());

    const data = res.data;
    const i = foodTrucks.findIndex(({ id }) => id == data.id);

    setFoodTrucks([
      ...foodTrucks.slice(0, i),
      res.data,
      ...foodTrucks.slice(i + 1),
    ]);
  };

  return (
    <>
      <Head>
        <title>All FoodTrucks Page</title>
        <meta name="description" content="Find a lot of great food-trucks" />
      </Head>
      <FoodTruckSearch onSearch={findFoodTruckHandler} />
      <FoodTruckList
        items={foodTrucks}
        toggleLike={likeHandler}
        toggleCollect={collectionHandler}
      />
    </>
  );
};
export default FoodTrucksPage;

export async function getStaticProps() {
  const allFoodTrucks = await getAllFoodTrucks();
  return {
    props: {
      allFoodTrucks,
    },
    revalidate: 60,
  };
}
